package cn.template.serve_project.util;

import cn.template.serve_project.constant.JwtConstant;
import cn.template.serve_project.enums.R;
import cn.template.serve_project.exception.BusinessException;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Objects;

/**
 * http工具类
 */
public class HttpUtil {


    //获取http信息
    public static HttpServletRequest getHttpInfo() {
        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
    }

    //获取令牌包含的用户信息
    public static Map<String, Object> getUserLoginInfo(HttpServletRequest request) {
        String token = request.getHeader(JwtConstant.TOKEN);
        if (Objects.isNull(token) || "".equals(token)) {
            throw new BusinessException(R.ERROR_LOGIN_NOT);
        }

        Map<String, Object> stringObjectMap = JwtUtil.parseToken(token);
        if (Objects.isNull(stringObjectMap)) {
            throw new BusinessException(R.ERROR_ATTESTATION_NO);
        }
        return stringObjectMap;
    }

    //获取令牌包含的用户信息
    public static Map<String, Object> getUserLoginInfo() {
        return getUserLoginInfo(getHttpInfo());
    }
}
